<?php
class Task_dailyAction extends TaskAction {

	function _initialize(){
		parent::_initialize();
		import("@.ORG.Task.Task_daily");
		$this->task=new Task_daily();
		$this->dao = D('Form');
	}
	public function index(){
		
		$taskDB=D('Task');
		$table = D('taskform')->where('site_id =' . __SITEID__ . ' and member_id = ' . $this->memberInfo['id'])->select();
		$this->integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__,'typename '=> 'Binte')) -> select();
		$this->isadmin=D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false);
		$this->inteType= M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
		//计算不同时间参数下的应提醒的数量
		$remind=[];
		$timeParam=['month','week',0,1,2,3,4,5,6];
		
		$sample=$taskDB->parmFilter($this->_param('status'),$this->_param('type'),$this->_param('important'),$this->_param('belong'));
		foreach($timeParam as $vo){
			$timeVal=is_int($vo)?$vo-date('w'):$vo;
			$map=$taskDB->timeFilter($timeVal);
			$remind[$timeVal]=$taskDB->alias('t')->where($map.' and '.$sample.' and isTop=4')->count();
			//dump($taskDB->getLastSQL());
		}
		$this->assign('remind',$remind);
		$this->assign('membernow',$this->memberInfo['id']);
		$this->assign('table', $table);
//		$this->freeman();
		$this->display();
	}
	//分类列表
	public function formList(){
		$this->table=D('taskform')->where('site_id ='.__SITEID__.' and member_id = '.$this->memberInfo['id'])->select();
	    $this->display();
	}
	//新加分类
	public function newType(){
		$last['id']=D('Taskform')->where('site_id ='.__SITEID__.' and member_id = '.$this->memberInfo['id'])->order('id desc')->getfield('id');
		$last['title']=D('Taskform')->where('site_id ='.__SITEID__.' and member_id = '.$this->memberInfo['id'])->order('id desc')->getfield('title');
//		$last='{id:"'.$last['id'].'",title:"'.$last['title'].'"}';
//		echo $last;
		echo json_encode($last);
	}
	//添加分类页面
	public function addform(){
		$this->display();
	}
	//删除分类
	public function deleteform(){
		if($this->_get('id')){
			$ret=D('taskform')->where('id='.$this->_get('id').' and site_id='.__SITEID__)->delete();
			echo(json_encode(['status'=>$ret]));exit;	
		}	
	}
	//插入分类
	public function insertform(){
		$taskformDB=D('Taskform');
		$insert=false;
		if(trim($_REQUEST['title'])!=''){
			if($taskformDB->where(['title'=>$_REQUEST['title'],'site_id'=>__SITEID__,'member_id'=>$this->memberInfo['id']])->count()==0){
				$map['title']=$_REQUEST['title'];
				$map['member_id']=$this->memberInfo['id'];
				$map['site_id']=__SITEID__;
				$insert=$taskformDB->add($map);
			}
		}
		if($insert){
			$this->success('添加成功');
		}else{
			$this->error('添加失败');
		}
	}
	//正在进行中的任务列表
	public function nowlist(){
		$taskDB=D('Task');
		$missionDB=D('mission');
		$taskformDB=D('taskform');
		//排序
		$listorder='isTop desc,id desc';
		if($this->_param('date')==='0'){
			$listorder='id,isTop desc';
		}
		if($this->_param('date')==='1'){
			$listorder='id desc,isTop desc';
		}
		if($this->_param('progress')==='0'){
			$listorder='progress desc,'.$listorder;
		}
		if($this->_param('progress')==='1'){
			$listorder='progress,'.$listorder;
		}

		//时间筛选模型
		$map=$taskDB->timeFilter($this->_param('time'));
		//参数和人员筛选模型
		$sample=$map.' and '.$taskDB->parmFilter($this->_param('status'),$this->_param('type'),$this->_param('important'),$this->_param('belong'));
		
		$count = $taskDB->alias('t')->where($sample)->count();
		//实例化分页类
		import('ORG.Util.Page');
		$p = new Page($count, 5);
		$task=$taskDB->alias('t')->where($sample)->limit($p->firstRow . ',' . $p->listRows) ->field('t.*')->order($listorder)->select();
		foreach($task as $key =>$value){
			if(!empty($value['type_id'])){
				$type=array_filter(explode(',',$value['type_id']));//分割type_id
// * 	如果用户没有设置过type_id，就显示发布者设置的type_id;
// * 	如果用户设置过type_id,就显示用户设置的type_id;
				foreach($type as $k =>$v){
					$check=$taskformDB->where('id ='.$v)->find();
					if($check['member_id']==$this->memberInfo['id']&&$check['site_id']==__SITEID__){
						$task[$key]['type_name']=$check['title'];
						$flag=true;
					}
				}
				if(!$flag){
					$mod=$taskformDB->where('id ='.$type[0])->find();
					$task[$key]['type_name']=$mod['title'];
				}
			}
//计算参与人数
			$missionRet=$missionDB->where(['task_id'=>$value['id']])->group('proposername')->getField('id',true);
			$task[$key]=array_merge($task[$key],['member_count'=>count($missionRet)]);
			//如果这个任务的进度小于50，且截止日期为这两天，那么isTop设置为4
			if($value['progress']<50&&$value['realtime']<strtotime('+2 day')){
				$taskDB->where('id='.$value['id'])->setField('isTop',4);
				//dump($taskDB->getLastSQL());
			}

			$difference=(strtotime(date('Y-m-d',$task[$key]['realtime']))-strtotime(date('Y-m-d',time())))/(24*3600);
			if($difference<0){
				$task[$key]['difference']='已过期';
			}elseif($difference==0){
				$task[$key]['difference']='今天截止';
			}else{
				$task[$key]['difference']='剩余'.$difference."天";
			}
		}
		$group=D('member')->alias('m')->join('think_member_group as g on m.group_id = g.id')->where('m.id ='.$this->memberInfo['id'])->find();
		$this->remind=$taskDB->alias('t')->where($sample.' and isTop=4')->count();
		$this->assign('group',$group['title']);
		$this->assign('task',$task);

		$pages = $p->show();
		$this->assign('pages', $pages);
		$this->display();
	}

	public function editType(){
		$map['id']=$this->_param('id');
		$sql=D('task')->where("id = ".$map['id'])->find();
		$type=array_filter(explode(',',$sql['type_id']));//分割type_id
///*
// * 	如果用户没有设置过type_id，就显示发布者设置的type_id;
// * 	如果用户设置过type_id,就显示用户设置的type_id;
// */

		foreach($type as $k =>$v){
			$check=D('taskform')->where('id ='.$v)->find();
			if($check['member_id']==$this->memberInfo['id']&&$check['site_id']==__SITEID__){//type_id中用户已设置
				unset($type[$k]);
			}
		}
		if(count($type)){//除了用户定义的以外，还有别人的type_id
			$newtype=implode(',',$type);//重新整合type_id
			$map['type_id']=$newtype.','.$this->_param('type_id');
		}else{
			$map['type_id']=$this->_param('type_id');
		}
		$edit=D('task')->save($map);
		if($edit){
			echo "修改成功";
		}else{
			echo "修改失败";
		}
	}

	public function donelist(){
		$taskDB=D('task');
		$count = $taskDB->alias('t')->join('think_taskform f on t.type_id = f.id')->where('t.site_id ='.__SITEID__.' and ( t.member_id ='.$this->memberInfo['id'].' or t.creator_id='.$this->memberInfo['id'].'  ) and t.progress = 100 and t.temptask = 0')->count();

		//实例化分页类
		import('ORG.Util.Page');
		$p = new Page($count, 5);
		$task=$taskDB->alias('t')->join('think_taskform f on t.type_id = f.id')->where('t.site_id ='.__SITEID__.' and ( t.member_id ='.$this->memberInfo['id'].' or t.creator_id='.$this->memberInfo['id'].'  ) and t.progress = 100 and t.temptask = 0')->limit($p->firstRow . ',' . $p->listRows) ->field('t.*,f.title as type_name')->order('id desc')->select();
		//dump($taskDB->getLastSQL());
		$group=D('member')->alias('m')->join('think_member_group as g on m.group_id = g.id')->where('m.id ='.$this->memberInfo['id'])->find();
		$this->assign('group',$group['title']);
		$this->assign('task',$task);

		$pages = $p->show();
		$this->assign('pages', $pages);
		$this->display();
	}
	//异步获取树状任务列表
	public function getTask(){
		echo(json_encode($this->task->selectall($this->task->filter())));
		
	}
	public function insert(){
        if(IS_POST){
			$_POST['starttime']=time();
			$_POST['realtime']=strtotime($_POST['realtime'])+24*3600-1;
			$_POST['reviewer_id']= $this->memberInfo['id'];
			$_POST['temptask']='0';
			if(isset($_POST['img_url'])){
				$_POST['img_url']=implode('^+^',$_POST['img_url']);
			}
			if(isset($_POST['mode'])){
				D('Info')->sendMsg([['tomemberid'=>$_POST['member_id'],'title'=>'任务','content'=>'您有了个新的标题为“'.$_POST['title'].'”的任务项目！','mode'=>implode(',',$_POST['mode']),'type'=>'remind','member_name'=>$_POST['member_name']]]);
			}
			if(isset($_POST['integral'])){
				$_POST['integralsum']=serialize([$_POST['member_id']=>['name'=>$_POST['member_name'],'integral'=>$_POST['integral']]]);
				$_POST['integralNum']=serialize($_POST['integral']);
			}
            if($this->task->insert_daily()){
				$this->success('发布成功！');
			}else{
				$this->error($this->task->getError());
			}
        }
	}
	public function makeTop(){
		M('Task')->where('id='.$_GET['id'])->setField('isTop',time());
	}
	public function update(){

		$name=str_replace('.','',substr($_POST['img_url'][count($_POST['img_url'])-1],-4));
		if($name=='doc'||$name=='docx'||$name=='xls'||$name=='xlsx'||$name=='ppt'||$name=='pptx'){
			echo 1;
			$flash=new FlashAction();
			$path=$flash->start($_POST['img_url'][count($_POST['img_url'])-1]);
			}
		
		$lwnfilepath=$_POST['img_url'][count($_POST['img_url'])-1].',';
		
		if($this->_get('id')){
			$task=$this->task->getinfo($_GET['id']);
			if($task['member_id']!=$this->UserInfo&&$task['creator_id']!=$this->UserInfo){
				die(json_encode(array('statu'=>0,'info'=>$task['creator_id'])));
			}
			if(isset($_POST['img_url'])){
			if($name=='doc'||$name=='docx'||$name=='xls'||$name=='xlsx'||$name=='ppt'||$name=='pptx'){
				$_POST['img_url']=$task['img_url'];
				}else{
				$_POST['img_url']=implode('^+^',$_POST['img_url']);
			}
			}
            $_POST['id']=$_GET['id'];
			if(isset($_POST['time'])){
                $_POST['time'] = strtotime($_POST['date']);
			}
			if(isset($_POST['starttime'])){
                $_POST['starttime'] = strtotime($_POST['starttime']);
			}
			if(isset($_POST['realtime'])){
                $_POST['realtime'] = strtotime($_POST['realtime']);
			}
			if(isset($_POST['form_id'])){
                $_POST['form_id']=implode(',',$_POST['form_id']);
			}
			if($name=='doc'||$name=='docx'||$name=='xls'||$name=='xlsx'||$name=='ppt'||$name=='pptx'){
			if($task['swf_path']!=''){
				$_POST['swf_path'].=$task['swf_path'].json_encode(array('swf'=>$path['swf'],'fname'=>$name)).'.*.';
				}else{
				$_POST['swf_path'].=json_encode(array('swf'=>$path['swf'],'fname'=>$name)).'.*.';
					}
				if($task['filepath']!=''){
				$_POST['filepath'].=$task['filepath'].$lwnfilepath.',';
				}else{
				$_POST['filepath'].=$lwnfilepath;
					}
			}
			$_POST['temptask']='0';
			$result=$this->task->update();
			//dump($result);
			if($result){
				$this->success('保存成功！');
			}else{
				$this->error($this->task->getError());

			};
		}
	}
	public function delete(){
		if(!$this->_get('id')){return $this->error('失败');}
		if($_POST['member_id']!=$this->UserInfo){
			die(json_encode(array('statu'=>0,'info'=>'错误，请不要越权操作！')));
		}
		if(!$this->task->delete($_GET['id'])){
			$this->error($this->task->getError());
		}else{
			$this->success('删除成功');
		};
	}
	//改变任务状态为通过
	public function pass(){
		if($this->_get('id')){
			$list=$this->task->getList($this->task->filter(['id'=>$_GET['id']]));
			foreach($list as $v){
				if($v['status']<3){
					$this->error('更改错误，子任务未完成。');
				}
			}
			$this->task->changeStatus($this->_get('id'),4);
			$this->success('成功');
		}
	}
	//失败
	public function fail(){
		if($this->_get('id')){
			$list=$this->task->getList($this->task->filter(['id'=>$_GET['id']]));
			foreach($list as $v){
				if($v['status']==='0'){
					$this->error('更改错误，子任务未完全失败。');
				}
			}
			$this->task->changeStatus($this->_get('id'),0);
			$this->success('成功');
		}
	}
	//任务评分页面(其中包括用户添加的另一个事件)
	public function score(){
		if($this->_get('id')){
			$taskid=$this->task->finalTask($_GET['id']);
			$list=$this->task->getList($this->task->filter(['id'=>$taskid]));
			$arr=[];
			$eventDB=D('Event');
			foreach($list as $k=>$v){
				$result=$eventDB->where(['task_id'=>$v['id']])->Field('id,member_id,membername,remark,integralnumber,task_id,mission_id')->select();
				if($result==0){continue;}
				foreach($result as $vo){
					if($vo['mission_id']!=0){$vo['remark']=$v['remark'];}
					$arr[]=$vo;
				}
			}
			$this->assign('score',$arr);
			$this->assign('taskid',$taskid);
			$this->display();
		}
	}
	//任务列表
	public function taskList(){
		if(IS_AJAX){
			$this->initView();

			D('Task')->_list($this->view,"members like '%,".$this -> memberInfo['id'].",%'",10);
			$this->display();
		}
	}
	//我的工作
	public function myTask(){
		if(IS_AJAX) {
			$taskDB=D('Task');
			$table = D('taskform')->where('site_id =' . __SITEID__ . ' and member_id = ' . $this->memberInfo['id'])->select();
			$this->integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__,'typename '=> 'Binte')) -> select();
			$this->isadmin=D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false);
			$this->inteType= M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
			//计算不同时间参数下的应提醒的数量
			$remind=[];
			$timeParam=['month','week',0,1,2,3,4,5,6];
			
			$sample=$taskDB->parmFilter($this->_param('status'),$this->_param('type'),$this->_param('important'),$this->_param('belong'));
			foreach($timeParam as $vo){
				$timeVal=is_int($vo)?$vo-date('w'):$vo;
				$map=$taskDB->timeFilter($timeVal);
				$remind[$timeVal]=$taskDB->alias('t')->where($map.' and '.$sample.' and isTop=4')->count();
				//dump($taskDB->getLastSQL());
			}
			$this->assign('remind',$remind);
			$this->assign('membernow',$this->memberInfo['id']);
			$this->assign('table', $table);
//			$this->freeman();
			$this->display();
		}
	}
	//考勤
	public function attendence(){
		$this->membertype=D('Member_position')->isLeader($this->memberInfo['id']);//是否管理层
//		$station=D('Member_position')->where("member_id like '%".$this->memberInfo['id']."%' ")->getfield('id',false);
		$this->time=$this->_param('time')?strtotime($this->_param('time')):time();//时间
		$this->timetype=$this->_param('timetype')?$this->_param('timetype'):'0';//年1或月0
		if($this->timetype==0){//月
			$start=strtotime(date('Y',$this->time).'-'.date('m',$this->time)."-1");
			if(date('m',$this->time)==12){
				$end=strtotime(date('Y-m-31 23:59:59',$this->time));
			}else{
				$end=strtotime(date('Y',$this->time).'-'.(date('m',$this->time)+1).'-1');
			}
		}else{//年
			$start=strtotime(date('Y',$this->time)."-1-1");//year start unixtime 2017-01-01 00:00:00
			$end=strtotime((date('Y',$this->time)+1)."-1-1");
		}
		$this->start=$start;
		$this->end=$end;
		if($this->_param('type')){
			$type=$this->_param('type');
			$type=explode('_',$type);
			$typeid=$type[0];//排序字段
			$typeval=$type[1];//排序方式 1正2倒
		}
		if((D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false))=='1'){
			$this->assign('isadmin',1);
			//老板
			if($this->_param('position_id')){
				$posid=$this->_param('position_id');
				$member=D('Member')->where("memberpositionid like '%,".$posid."%,'")->getfield('id',true);
			}else{//没有部门就搜站点所有人
				$member=D('Member')->where('site_id ='.__SITEID__)->getfield('id',true);
			}
			$this->showattendence($member,$start,$end,$typeid,$typeval,$list='');
			$this->display();
			die();
		}elseif($this->membertype==1){//主管
			$posid=D('Member_position')->where('member_id = '.$this->memberInfo['id'])->getfield('id',false);
			$member=D('Member')->where("memberpositionid like '%,".$posid."%,'")->getfield('id',true);
			$this->showattendence($member,$start,$end,$typeid,$typeval,$list='');
			$this->display();
			die();
		}else{
			//员工
			$this->display('attdetail');
		}
	}

	public function attdetail(){
		//个人，考勤详情
		$map['member_id']=$this->_param('member');
		if($this->_param('start')&&$this->_param('end')){
			$start=$this->_param('start');
			$end=$this->_param('end');
		}else{
			$start=strtotime(date('Y',$this->time)."-1-1");//year start unixtime 2017-01-01 00:00:00
			$end=strtotime((date('Y',$this->time)+1)."-1-1");
		}
		$map['createtime']=array('between',array($start,$end));
		$map['particular']=array('in',array('1','3','4'));
		$sql=D('Mission')->where($map)->order('createtime desc')->field('id,title,formtemplate,integralret,createtime,stime,etime')->select();
		$this->assign('list',$sql);
		$this->display();
	}

	public function showattendence($member,$start,$end,$typeid='',$typeval='',$list=''){
		$map['createtime']=array('between',array($start,$end));
		foreach($member as $key =>$val){//部门中的每个人
			if(!$this->_param('position_id')){//是否传入position_id
				$posid=D('Member')->where('id = '.$val)->getfield('memberpositionid',false);
				$posid=array_filter(explode(',',$posid));//数组
				if($posid){
					$position='';
					foreach($posid as $key =>$v){
						$posname=D('Member_position')->where('id = '.$v)->getfield('name',false);
						$position=$position.$posname.'/';
					}
					$position=substr($position,0,-1);
				}else{
					$position='';
				}
			}else{
				$position=D('Member_position')->where('id = '.$this->_param('position_id'))->getfield('name',false);
			}
			$map['member_id']=$val;
			$map['particular']=1;
			$man=D('Member')->where('id = '.$val)->field('name,nickname,username')->find();
			$username=$man['name']?$man['name']:$man['nickname'];
			$man=$username?$username:$man['username'];
			$leave=D('Attendence')->where($map)->field('member_id,sum(endtime-starttime) as time')->find();
			$leavehour=ceil($leave['time']/3600);//请假小时
			$leavecount=D('Attendence')->where($map)->count();//请假次数
			$map['particular']=3;
			$neglect=D('Attendence')->where($map)->count();//旷工次数(一次即一天)
			$map['particular']=4;
			$madman=D('Attendence')->where($map)->field('member_id,sum(endtime-starttime) as time')->find();
			$madhour=ceil($madman['time']/3600);//加班小时
			$madcount=D('Attendence')->where($map)->count();//加班次数
			$list[]=array('id'=>$val,'man'=>$man,'member_id'=>$val,'position'=>$position,'leavehour'=>$leavehour,'leavecount'=>$leavecount,'neglect'=>$neglect,'madhour'=>$madhour,'madcount'=>$madcount);
		}

		$list = $this->my_sort($list,'madhour',SORT_DESC,SORT_NUMERIC);
		foreach($list as $k =>$v){
			$list[$k]['madsort']=$k+1;
		}
		foreach($list as $k =>$v){
			$list[$k]['emptyhour']=$v['leavehour']+8*$v['neglect'];
		}
		$list = $this->my_sort($list,'emptyhour',SORT_ASC,SORT_NUMERIC);
		foreach($list as $k =>$v){
			$list[$k]['onduty']=$k+1;
		}
		//3 加班时长 4出勤排序 5加班排序 6请假时间 7请假次数
		if($typeid != ''){
			switch($typeid){
				case 3 :
					$sortcolum='madhour';break;
				case 4 :
					$sortcolum='onduty';break;
				case 5 :
					$sortcolum='madsort';break;
				case 6 :
					$sortcolum='leavehour';break;
				case 7 :
					$sortcolum='leavecount';break;
			}
			switch($typeval){
				case 1 :
					$sort=SORT_ASC;break;
				case 2 :
					$sort=SORT_DESC;break;
			}
			$list= $this->my_sort($list,$sortcolum,$sort,SORT_NUMERIC);
		}
		import('ORG.Util.Page');
		$count=count($list);
		$p=new Page($count,15);
		$list=array_slice($list,$p->firstRow,$p->listRows);
		$pages=$p->show();
		$this->assign('list',$list);
		$this->assign('pages', $pages);
	}
	/*
	 * 多维数组排序
	 *
	 * 	SORT_ASC - 默认，按升序排列。(A-Z)
	 * 	SORT_DESC - 按降序排列。(Z-A)
	 * 	随后可以指定排序的类型：
	 * 	SORT_REGULAR - 默认。将每一项按常规顺序排列。
	 * 	SORT_NUMERIC - 将每一项按数字顺序排列。
	 * 	SORT_STRING - 将每一项按字母顺序排列
	 * */
	public function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
		if(is_array($arrays)){
			foreach ($arrays as $array){
				if(is_array($array)){
					$key_arrays[] = $array[$sort_key];
				}else{
					return false;
				}
			}
		}else{
			return false;
		}
		array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
		return $arrays;
	}
	//是否有任务
	private function freeman(){

		//判断当前是否有任务
		if((D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false))=='1'){
			$member=D('Member')->where('site_id ='.__SITEID__)->getfield('id',true);//查找公司所有人
		}else{
			$memberposition=D('Member')->where('id = '.$this->memberInfo['id'])->getfield('memberpositionid',false);
			$memberposition=array_filter(explode(',',$memberposition));
			$memmap='';
			foreach($memberposition as $key =>$val){
				$memmap.=" memberpositionid like '%".$val."%' or";
			}
			$memmap=substr($memmap,0,-2);
			$member=D('Member')->where($memmap)->getfield('id',true);
		}
		$checkman=D('Mission')->where('site_id ='.__SITEID__.' and state != 3 and state != 1')->distinct(true)->getfield('member_id',true);//项目未完成
		$arr=array();
		foreach($member as $key =>$val){
			if(!in_array($val,$checkman)){
				$arr[]=$val;
			}
		}
		$arrmap['id']  = array('in',$arr);
		$freeman=D('Member')->where($arrmap)->getfield('name',true);
		$this->assign('freeman',$freeman);
	}
	//添加页面
	public function add(){
		//$this->assign('taskList',$this->task->getList($this->task->filter(['pid'=>0])));
		$this->display();
	}
	//修改页面
	public function edit(){
		if($this->_get('id')){
			$missionDB=D('Mission');
			$memberDB=D('Member');
			$this -> initView();

			$info=$this->task->getinfo($_GET['id']);
			$this->assign('info',$info);
			if(!empty($info['img_url'])){
				$img=explode('^+^',$info['img_url']);
				$this->imgurl=array_filter($img);
			}
				if(!empty($info['swf_path'])){
		
				$swf=explode('.*.',$info['swf_path']);
		
				$swf_array=array_filter($swf);
				//$this->swfpath
				$swf=array();
			 foreach($swf_array as $key => $val){
					$swf[$key]=json_decode($val);
			 }
					
		     $swf_array=array();
		     $i=0;
			 foreach($swf as $skey => $sval){
			 foreach($sval as $askey => $asval){
			    if($askey == 'swf'){
			    $swf_array['swf'][$i]=$asval;
			        }		
			    if($askey == 'fname'){
				$doc_array['fname'][$i+1]=$asval;	  
					  }
		         }
		     $i++;
			}
		    $this->swfpath=$swf_array['swf'];
			$this->docname=$doc_array['fname'];
			}
			
//			var_dump($this->imgurl);exit;
			//$category=M('formcategory')->where(['site_id'=>__SITEID__,'name'=>'积分管理'])->getField('id');
			$table=D('taskform')->where('site_id ='.__SITEID__.' and member_id = '.$this->memberInfo['id'])->select();

			//分别获取任务里工作的积分
			$mission=$missionDB->where(['task_id'=>$_GET['id']])->getField('id,proposername,member_id,integralret');
			/*$inteRet=[];
			foreach($mission as $k=>$v){
				$merge=['name'=>$v['proposername']];
				$ret=empty($v['integralret'])?$missionDB -> where(array('id' => $k)) -> geteventIntegral($this->view):unserialize($v['integralret']);

				if(isset($inteRet[$v['proposername']])){
					foreach($ret as $ke=>$va){
						$inteRet[$v['proposername']][$ke]=(int)$inteRet[$v['proposername']][$ke]+(int)$va;
					}

				}else{
					$inteRet[$v['proposername']] = $ret;
				}
			}*/
			
			//如果任务已经完成，检测审批表是否有相应的审批，无则创建一个
			if($info['status']==3&&$info['member_id']==$this->memberInfo['id']){
				$ret=$missionDB->where(['task_hide_id'=>$info['id']])->find();
				if($ret==false){
					$integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
					foreach($integraltype as $k => $v){
						$formula[] = "proposer:".$v['typename']."=".intval($_POST[$v['typename']]);
						$value[] = '申请'.$v['remark'].'：'.intval($_POST[$v['typename']]);
					}
					$data['formula'] = implode(',', $formula);
					$data['formtemplate'] = $info['remark'];
					$data['formtemplateText'] = $info['remark'];
					$data['form_id'] = 0;
					$data['state']=1;
					$data['member_id'] = $this -> memberInfo['id'];
					$data['approver_id'] = $this->memberInfo['pid'];
					$data['approvername']=$memberDB->where('id='.$data['approver_id'])->getField('name');;
					$data['proposername']=$this->memberInfo['name'] != '' ? $this->memberInfo['name'] : $this->memberInfo['nickname'];
					$data['starttime']=$info['starttime'];
					$data['endtime']=$info['endtime'];
					$data['missionType'] = 1;
					$data['title'] = $this -> memberInfo['name'].'的任务完成表';
					$data['record'] = build_order_no();
					$data['site_id'] = __SITEID__;
					$data['createtime'] = time();
					$data['detail'] = $info['remark'];
					$data['task_hide_id']=$info['id'];
					$info['endtime']=time();
					$info['detail']=$info['remark'];
					$data['integralNum']=$info['integralNum'];
					$data['object']=serialize($info);
					$ret = $missionDB->add($data);
					//$ret=$missionDB->where(['id'=>$ret])->find();
				}
				//$this->ret=$ret;
			}
			
			$InteType = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
			$InteTypeList = array();
			foreach($InteType as $k => $v){
				$InteTypeList[$v['typename']] = $v['remark'];
			}
			$this->InteTypeList = $InteTypeList;
			$inteRet = unserialize($info['integralsum']);
			$this->assign('inteRet',$inteRet);
			$this->assign('table',$table);
			$this->assign('formList',M('Form')->where(['site_id'=>__SITEID__,'name'=>'任务通知单'])->select());
			$this->display();
		}
	}
	//积分修改页面的积分明细结果
	public function inteRet(){
		if($_GET['id']){
			$InteType = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
			$InteTypeList = array();
			foreach($InteType as $k => $v){
				$InteTypeList[$v['typename']] = $v['remark'];
			}
			$this->InteTypeList = $InteTypeList;
			$inteRet=$this->task->getinfo($_GET['id'],'integralsum,integralNum');
			$this->info=unserialize($inteRet['integralsum']);
			//dump($this->info);exit;
		}$this->display();
	}
	//显示当前任务和相关任务的信息
	public function view(){
		if($this->_get('id')){
			$info=$this->task->getinfo($_GET['id']);
			$this->assign('info',$info);
			$this->assign('infoChildren',$this->task->selectall(['pid'=>$this->_get('id')]));
			$this->assign('infoParent',$this->task->getinfo($info['pid']));
			$this->assign('progress',$this->task->getProgress(['task_id'=>$_GET['id']]));
			$this->display();
		}
	}
	//新建进度
	public function newProgress(){
		if($this->_get('id')){
			$this->assign('info',$this->task->getinfo($_GET['id']));
			$this->display();
		}
	}
	//显示进度
	public function progressList(){
		if($this->_get('id')){
			$this->assign('info',$this->task->getProgress(['task_id'=>$_GET['id']]));
			$this->display();
		}
	}
	//更新进度
	public function progressInsert(){
		if(IS_POST){
			$_POST['datetime']=time();
			$_POST['member_id']=$this->UserInfo;
			$_POST['member_name']=$this->userInfo['name'];
			$_POST['img_url']=$this->userInfo['img_url'];
			if($this->task->newProgress()){
				die(['statu'=>1]);
			}else{
				die(['statu'=>0,'info'=>$this->task->getError()]);
			}
		}
	}
	//分发任务
	public function distribution(){
		if(IS_POST&&$_POST['member_id']){
			if(!$this->task->distribution()){
				die(json_encode(array('statu'=>1)));
			}else{
				die(json_encode(array('statu'=>0,'info'=>$this->task->getError())));
			};
		}
	}

	//临时任务首页
	public function tempTask(){
		$count = D('mission')->where('temptask = 1 and member_id =0 ')->count();
		$pagesize=5;
		//实例化分页类
		import('ORG.Util.Page');
		$p = new Page($count,$pagesize);
		$tasklist=D('mission')->where("temptask = 1 and member_id =0 ")->limit($p->firstRow . ',' . $p->listRows)->order('id desc') ->select();
		$pages = $p->show();
		$this->assign('temptask',$tasklist);
		$this->assign('pages', $pages);
		$this->display();
	}
	public function tempDone(){
		$pagesize=5;
		$missionDB=D('Mission');
		$listmap="temptask = 1 and member_id =".$this->UserInfo;
		$count = $missionDB->where($listmap)->count();
		//实例化分页类
		import('ORG.Util.Page');
		$p = new Page($count,$pagesize);
		$taskdone=$missionDB->where($listmap)->limit($p->firstRow . ',' . $p->listRows)->order('id desc') ->select();
		$pages = $p->show();
		$this->assign('tempdone',$taskdone);
		$this->assign('pages', $pages);
		$this->display();
	}
	//临时任务查看
	public function tempview(){
		if($this->_param('id')){
			$myform=D('mission')->where('id = '.$this->_param('id'))->find();
			$this->assign('myform',$myform);
			$this->assign('html',$myform['formtemplate']);
			$this->display();
		}
	}
	//临时任务获取表单
	public function tempForm(){
		if($this->_param('pid')){
			$this->assign('pid',$this->_param('pid'));
		}else{
			$this->assign('pid',time());
		}
		if($this->_param('pid')){
			$this->assign('myadd',D('mission')->where('pid ='.$this->_param('pid'))->select());
		}
		$this->assign('tempform',D('form')->where('site_id ='.__SITEID__)->select());
		$this->display();
	}

    public function change(){
        $map['formula']=array('neq','');
        $this->taskform = M('Form') -> where($map) -> select();
		//$this->formcategory=D('Formcategory')->where(['site_id'=>__SITEID__,'status'=>1])->select();
		$this->assign('formcategorylist',D('Formcategory')->getList());
        $this->display();
    }

	public function tempget(){
		$data['id']=$this->_param('id');
		$data['member_id']=$this->memberInfo['id'];
		$data['approver_id']=D('Member')->where('id='.$data['member_id'])->getField('pid');
		$data['state']=-1;
		$data['proposername'] = $this->memberInfo['name'];
		$tempget=D('Mission')->save($data);
		echo $tempget?'领取成功':"领取失败";
	}
	public function tempadd(){
		if($this->_param('pid')){
			$pid=$this->_param('pid');
			$this->assign('newbee',D('Mission')->where('pid = '.$pid)->select());
			$this->display();
		}
	}
	public function ajaxdelete(){
		$id=$this->_param('id');
		$delete=D('Mission')->where('id = '.$id)->delete();
		if($delete){
			echo "删除成功";
		}else{
			echo "删除失败";
		}
	}
	public function integral(){
		$this->membertype=D('Member_position')->isLeader($this->memberInfo['id']);//ismanager
		$start=strtotime(date('Y',time()).'-'.date('m',time())."-1");
		if(date('m',time())==12){
			$end=strtotime(date('Y-m-31 23:59:59',time()));
		}else{
			$end=strtotime(date('Y',time()).'-'.(date('m',time())+1).'-1');
		}
		//boss
		if((D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false))=='1'){
			$this->assign('isadmin',1);
			//各部门工作分对比 总积分、人均积分
			$position=D('Member_position')->where('site_id = '.__SITEID__)->getfield('id',true);
			$total=array();
			$posarr=array();//所有部门
			$intarr=array();//部门总积分
			foreach($position as $key => $val){
				$memtotal=D('Member')->where("memberpositionid like '%,".$val.",%'")->count();//部门所有员工
				$position=D('Member_position')->where("id = ".$val)->getfield('name');
				//员工总数、员工总积分、人均积分
				$postotal=$this->groupTotal($val);
				$average=round(($postotal['add']-$postotal['cut'])/$memtotal,2);
				$total[]=array('total'=>$postotal['add']-$postotal['cut'],'num'=>$memtotal,'position'=>$position,'average'=>$average);
				//各部门积分分布
				$posarr[]=$position;
				$intarr['add'][]=$postotal['add'];
				$intarr['cut'][]=$postotal['cut'];
			}
			$this->assign('posarr',json_encode($posarr));
			$this->assign('addarr',json_encode($intarr['add']));
			$this->assign('cutarr',json_encode($intarr['cut']));
			$this->total=$total;
			//部门奖扣分对比 奖扣分数量、次数
			$leader=D('Member_position')->where('site_id = '.__SITEID__)->getfield('member_id',true);
			$myinte=array();
			foreach($leader as $key =>$val){
				if($val){//管理者不为空
					$position=D('Member_position')->where('member_id ='.$val)->getfield('name',false);
					$inte=D('Member')->where('id = '.$val)->getfield('integralconfig');
					$inte=unserialize($inte);
					$addinlaw=$inte['Binte']['0']?$inte['Binte']['0']:0;//应奖
					$cutinlaw=$inte['Binte']['1']?$inte['Binte']['1']:0;//应扣
					$addmap['time']=array('between',array($start,$end));
					$addmap['rewarder_id']=$val;
					$addmap['changenum']=array('gt',0);
					$add=D('Integral_log')->where($addmap)->getfield('sum(changenum)');//已奖
					$add=$add?$add:0;
					$addnum=D('Integral_log')->where($addmap)->count();//奖励次数
					$addmap['changenum']=array('lt',0);
					$cut=D('Integral_log')->where($addmap)->getfield('sum(changenum)');//已扣
					$cut=$cut?$cut:0;
					$cutnum=D('Integral_log')->where($addmap)->count();//奖励次数
					$myinte[]=array('add'=>$add,'addnum'=>$addnum,'addinlaw'=>$addinlaw,'cut'=>abs($cut),'cutnum'=>$cutnum,'cutinlaw'=>$cutinlaw,'position'=>$position);
				}
			}
			$this->myinte=$myinte;
		}else{
			if($this->membertype){//manager
				$this->assign('isLeader',1);
				//本部门奖扣分数量、次数 按人排名
				$position=$position=D('Member_position')->where('member_id = '.$this->memberInfo['id'])->getfield('id',false);
				$member=D('Member')->where("memberpositionid like'%,".$position.",%'")->getfield('id',true);
				$inte=array();
				foreach($member as $key =>$val){
					//针对每个人，计算 奖扣分总数、奖扣分次数
					$intmap['rewarder_id']=$this->memberInfo['id'];
					$intmap['site_id']=__SITEID__;
					$intmap['member_id']=$val;
					$intmap['changenum']=array('gt',0);
					$push=D('Integral_log')->where($intmap)->getfield('sum(changenum)');//奖
					$pushnum=D('Integral_log')->where($intmap)->count();//奖次数
					$intmap['changenum']=array('lt',0);
					$pull=D('Integral_log')->where($intmap)->getfield('sum(changenum)');//扣
					$pullnum=D('Integral_log')->where($intmap)->count();//扣次数
					$memname=D('Member')->where('id = '.$val)->getfield('name');
					$inte[]=array('memname'=>$memname,'push'=>$push,'pushnum'=>$pushnum,'pull'=>abs($pull),'pullnum'=>$pullnum);
				}
				$inte= $this->my_sort($inte,'push',SORT_DESC,SORT_NUMERIC);
				$inte=array_slice($inte, 0, 5);
				$this->inte=$inte;
				//已奖未奖次数
				$inte=unserialize($this->userInfo['integralconfig']);
				$this->cutinlaw=$inte['Binte']['3']?$inte['Binte']['3']:0;//应奖扣次数
				$this->cutinreal=D('Integral_log')->where('rewarder_id ='.$this->memberInfo['id'])->count();//实际奖扣次数
				$this->cutundo=$this->cutinlaw-$this->cutinreal;
				// 审批（已审、未审、总数）
				$missioncount = array();
				$mimap = "(reviewer_id='".$this->memberInfo['id']."' or approver_id = ".$this ->memberInfo['id']." or approver like '%,".$this->memberInfo['id'].",%')";
				$missioncount['all'] = D('Mission')->where($mimap.' and state <> -1') -> count();
				$missioncount['doing'] = D('Mission')->where($mimap.' and state = 1') -> count();
				$missioncount['done'] = $missioncount['all']-$missioncount['doing'];
				$this->assign('missioncount', $missioncount);
			}
			//每个积分事件的rule_id 统计所得积分（奖分）
			$event=D('Integral_log')->alias('i')->join('__INTEGRAL_RULETYPE__ r on r.id =i.rule_id and r.site_id ='.__SITEID__)->where('i.member_id = '.$this->memberInfo['id'].' and i.changenum >0')->group('rule_id')->field('r.name as name,sum(i.changenum) as sum')->select();
			$eventtype=array();
			$eventnum=array();
			foreach($event as $key =>$val){
				$eventtype[]=$val['name'];
				$eventnum[]=$val['sum'];
			}
			$this->eventtype=json_encode($eventtype);
			$this->eventnum=json_encode($eventnum);
			//每个积分事件的rule_id 统计所得积分（扣分）
			$cutevent=D('Integral_log')->alias('i')->join('__INTEGRAL_RULETYPE__ r on r.id =i.rule_id and r.site_id ='.__SITEID__)->where('i.member_id = '.$this->memberInfo['id'].' and i.changenum<0')->group('rule_id')->field('r.name as name,-sum(i.changenum) as sum')->select();
			$cuteventtype=array();
			$cuteventnum=array();
			foreach($cutevent as $key =>$val){
				$cuteventtype[]=$val['name'];
				$cuteventnum[]=$val['sum'];
			}
			$this->cuteventtype=json_encode($cuteventtype);
			$this->cuteventnum=json_encode($cuteventnum);

			//我的积分事件
			$this->initView();
			$map['member_id']=$this->memberInfo['id'];
//			$map['time']=array('between',array($start,$end));
			$field='r.remark as title,r.changenum as changenum,t.remark as type,r.time as time';
			$this->list=D('Integral_log')->alias('r')->join('__INTEGRAL_TYPE__ t on t.id =r.type_id and t.site_id = '.__SITEID__)->where($map)->field($field)->order('time desc')->limit(6)->select();
			//积分事件分类
			//找到integral_log，group by(rule_id)
			$ruleid=D('Integral_log')->where('member_id = '.$this->memberInfo['id'])->group('rule_id')->getfield('rule_id',true);
			//var_dump($ruleid);
			foreach($ruleid as $key =>$val){
				$rulename=D('Integral_ruletype')->where('id = '.$val)->getfield('name',false);
				$logsql=D('Integral_log')->where('member_id ='.$this->memberInfo['id']." and rule_id =".$val)->order('time desc')->limit(6)->field('remark,changenum')->select();
				$rule[$rulename]['son']=$logsql;
			}
			$this->memberid=$this->memberInfo['id'];
			$this->log=$rule;//将积分事件都写入$rule里了
		}
		$this->display();
	}
	public function groupTotal($posid){//部门总积分$posid
		$start=strtotime(date('Y',time()).'-'.date('m',time())."-1");
		if(date('m',time())==12){
			$end=strtotime(date('Y-m-31 23:59:59',time()));
		}else{
			$end=strtotime(date('Y',time()).'-'.(date('m',time())+1).'-1');
		}
		$member=D('Member')->where("memberpositionid like '%,".$posid.",%'")->getfield('id',true);//部门所有员工
		$count='';
		foreach($member as $key => $val){
			$map['member_id']=$val;
			$map['time']=array('between',array($start,$end));
			$map['changenum']=array('gt',0);
			$count['add']+=D('Integral_log')->where($map)->getfield('sum(changenum)');
			$map['changenum']=array('lt',0);
			$count['cut']+=D('Integral_log')->where($map)->getfield('sum(-changenum)');
		}
		return($count);
	}
}